const aiIcon = document.getElementById('aiIcon');
const aiAssistant = document.getElementById('aiAssistant');
const aiContent = document.getElementById('aiContent');
const aiInput = document.getElementById('aiInput');
const aiSendBtn = document.getElementById('aiSendBtn');
const questionUrl = window.config.backendapiUrl+"/question";
// 显示和隐藏 AI助手
aiIcon.addEventListener('click', () => {
    aiAssistant.style.display = aiAssistant.style.display === 'flex' ? 'none' : 'flex';
});

// AI助手发送消息
aiSendBtn.addEventListener('click', async () => {
    const question = aiInput.value.trim();
    if (!question) {
        alert('请输入您的问题！');
        return;
    }

    const userMessage = document.createElement('div');
    userMessage.textContent = `用户: ${question}`;
    userMessage.style.color = '#333';
    aiContent.appendChild(userMessage);

    const aiMessage = document.createElement('div');
    aiMessage.textContent = 'AI: 正在思考...';
    aiMessage.style.color = '#3b82f6';
    aiContent.appendChild(aiMessage);

    aiInput.value = ''; // 清空输入框

    try {
        console.log(question);
        const response = await fetch(questionUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ text: question }),
        });
        console.log(response);
        if (!response.ok) {
            throw new Error('请求失败');
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let done = false;
        let responseText = '';

        while (!done) {
            const { value, done: readerDone } = await reader.read();
            done = readerDone;
            responseText += decoder.decode(value, { stream: true });
            aiMessage.textContent = `AI: ${responseText}`;
            aiContent.scrollTop = aiContent.scrollHeight; // 滚动到最新消息
        }
    } catch (error) {
        aiMessage.textContent = `AI: 请求失败 - ${error.message}`;
        aiMessage.style.color = 'red';
    }
});